package com.apes.fn.ssm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.ssm.model.BrandPriority;
import com.apes.fn.ssm.model.FittingMessage;
import com.apes.fn.ssm.model.StockConfig;
import com.apes.fn.ssm.repository.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.BrandRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 *
 *@Description : 测算备货配置
 * @Author : WSl
 */
@Service("stockConfigService")
public class StockConfigService extends DomainService {

    @Autowired
    private StockConfigRepository stockConfigRepository;

    @Autowired
    private FittingMessageRepository fittingMessageRepository;

    @Autowired
    private LocationRepository locationRepository;

    /**
     * 批量更新备货配置
     *
     */
    public Map batchUpdateStockConfig(SimpleRequest request){

        //新增和修改
        List<StockConfig> stockConfigList = request.getA("stockConfigItems", StockConfig.class);
        Set<String> stockConfigSet = new HashSet();

        //禁止添加重复数据
        stockConfigList.forEach( stockConfig -> {
            String sole =  stockConfig.getLocation().getId() + stockConfig.getFittingName().getId();
            if (!stockConfigSet.add(sole)) throw new RuntimeException("请勿添加重复数据，请检查添加数据是否正确！");
        });

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))){
            List<StockConfig> delStockConfigs = request.getA("del", StockConfig.class);
            delStockConfigs.forEach(stockConfig -> {
                String sole = stockConfig.getLocation().getId() + stockConfig.getFittingName().getId();
                if (Objects.nonNull(stockConfig.getId()) && stockConfigSet.add(sole)){
                    stockConfigRepository.delete(stockConfig);
                }
            });
        }

        // 存在添加重复数据，先删除后添加
        List<StockConfig> resultStockConfigs = stockConfigList.stream().map(stockConfig -> {
            StockConfig oldStockConfig = stockConfigRepository.findOne(stockConfig.getLocation().getId(), stockConfig.getFittingName().getId());
            if (Objects.nonNull(oldStockConfig)) stockConfigRepository.delete(oldStockConfig);
            return stockConfigRepository.saveAndFlush(stockConfig);
        }).collect(Collectors.toList());
        Map stockConfigItems = MapUtil.mapper("stockConfigItems", resultStockConfigs);
        return stockConfigItems;
    }


    /**
     * 删除测算品牌优先级
     */
    private void deleteStockConfig(SimpleRequest request){
        JSONObject object = request.getJO();
        if (Objects.isNull(object.get("location")) && Objects.isNull(object.get("fittingName"))
                && Objects.isNull(object.get("valid"))) {
            stockConfigRepository.deleteAllInBatch();
        }else {
            List<Map<String, Object>> brandPriorityList = findAllManual(request);
            brandPriorityList.forEach( item -> stockConfigRepository.delete(item.get("id").toString()));
        }
    }


    /**
     * 定制导入品牌优先级配置
     *
     */
    public JSONObject importStockConfig (SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {
        List distinct = Collections.synchronizedList(new ArrayList());
        Map<String, Map<String, Object>> cacheLocation = new ConcurrentHashMap<>();
        Map<String, Map<String, Object>> cacheFittingMessage = new ConcurrentHashMap();
        AtomicReference key = new AtomicReference();
        Set locationAndFittingMessage = new HashSet();

        JSONArray titleArray = new JSONArray(15);
        titleArray.add("编号");
        titleArray.add("仓库");
        titleArray.add("仓库名称");
        titleArray.add("组合配件名称");
        titleArray.add("SKU覆盖率");
        titleArray.add("SKU上限");
        titleArray.add("SKU下限");
        titleArray.add("数量上限");
        titleArray.add("数量下限");
        titleArray.add("数量梯度");
        titleArray.add("会员基数");
        titleArray.add("版本号");
        titleArray.add("状态");
        titleArray.add("有效");
        titleColumnArray.add(titleArray);

        List dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach( item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;

                String locationId = iValueArray.get(0).toString();
                String fittingMessageName = iValueArray.get(2).toString();
                String SKUCover = iValueArray.get(3).toString();
                String SKUMax = iValueArray.get(4).toString();
                String SKUMin = iValueArray.get(5).toString();
                String QTYMax = iValueArray.get(6).toString();
                String QTYMin = iValueArray.get(7).toString();
                String qtyGraded = iValueArray.get(8).toString();
                String vipQty = iValueArray.get(9).toString();
                Boolean valid = iValueArray.get(10).toString().equals("是");
                JSONArray newDataArray = new JSONArray(15);
                if (Pattern.matches("[\\u4e00-\\u9fa5]*", locationId)) {    // 匹配中文
                    return;
                }
                Map<String, Object> location = this.cacheLocation_new(locationId, cacheLocation);
                Map<String, Object> fittingMessage = this.cacheFittingMessage_new(fittingMessageName, cacheFittingMessage);
                StockConfig stockConfig = stockConfigRepository.findOne(locationId, fittingMessage.get("id").toString());

                if (!locationAndFittingMessage.add(location.get("id") + fittingMessage.get("id").toString())) throw new RuntimeException("导入重复数据，请重新导入！");

                newDataArray.add(Objects.isNull(stockConfig)? "" : stockConfig.getId());
                newDataArray.add(location);
                newDataArray.add(location.get("name"));
                newDataArray.add(fittingMessage);
                newDataArray.add(SKUCover);
                newDataArray.add(SKUMax);
                newDataArray.add(SKUMin);
                newDataArray.add(QTYMax);
                newDataArray.add(QTYMin);
                newDataArray.add(qtyGraded);
                newDataArray.add(vipQty);
                newDataArray.add(Objects.isNull(stockConfig)? "" : stockConfig.getVersion());
                newDataArray.add(null);
                newDataArray.add(valid);



                dataList.add(MapUtil.mapped(newDataArray));
                distinct.add(locationId + fittingMessageName);
            });
        });

        titleColumnArray.addAll(dataList);
        return key.get().toString();
    }

    // 导入 - 缓存已查过的商品
    private Map<String, Object> cacheFittingMessage_new(String fittingMessageName, Map<String, Map<String, Object>> cacheProduct) {
        if (cacheProduct.get(fittingMessageName) == null) {
            FittingMessage fittingMessage = fittingMessageRepository.findOneName(fittingMessageName);
            Optional.ofNullable(fittingMessage).orElseThrow( ()-> new RuntimeException("没有找到对应组合配件的记录，组合配件名称为：" + fittingMessageName) );
            cacheProduct.put(fittingMessageName, MapUtil.mapper("id", fittingMessage.getId(), "name", fittingMessage.getName()));
        }
        return cacheProduct.get(fittingMessageName);
    }

    // 导入 - 缓存已查过的仓库
    private Map<String, Object> cacheLocation_new(String locationId, Map<String, Map<String, Object>> cacheLocation) {
        if (cacheLocation.get(locationId) == null) {
            Location location = locationRepository.findOne(locationId);
            Optional.ofNullable(location).orElseThrow( ()-> new RuntimeException("没有找到对应仓库编码的记录，仓库编码为：" + locationId) );
            cacheLocation.put(locationId, MapUtil.mapper("id", location.getId(), "name", location.getName()));
        }
        return cacheLocation.get(locationId);
    }


    /**
     * 手动查找优先级配置
     * @param request
     * @return
     */
    public List<Map<String, Object>> findAllManual(SimpleRequest request){
        JSONObject object = request.getJO();

        if (Objects.isNull(object.get("location")) && Objects.isNull(object.get("fittingName"))
                && Objects.isNull(object.get("valid"))) {
            throw new RuntimeException("查询条件不能为空!!!");
        }
        //按条件查询
        JSONArray resultArray = SpringManager.getBean(StockConfigDao.class).queryStockConfig(object);

        //拼装前端展示数据
        List result = resultArray.stream().map(
                item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    return  MapUtil.mapper(
                            "inquirySelectState",false,//多选款默认不勾选
                            "id",jsonObject.getString("ID"),
                            "location",MapUtil.mapper("id",jsonObject.getString("LOCATION_ID"),"name",jsonObject.getString("LOCATION_NAME")),
                            "fittingName",MapUtil.mapper("id",jsonObject.getString("FITTING_MESSAGE_ID"),"name",jsonObject.getString("FITTING_NAME")),
                            "SKUCover",jsonObject.getDouble("SKU_COVER"),
                            "SKUMax",jsonObject.getInteger("SKU_MAX"),
                            "SKUMin",jsonObject.getInteger("SKU_MIN"),
                            "QTYMax",jsonObject.getInteger("QTY_MAX"),
                            "QTYMin",jsonObject.getInteger("QTY_MIN"),
                            "qtyGraded",jsonObject.getInteger("QTY_GRADED"),
                            "vipQty",jsonObject.getInteger("VIP_QTY"),
                            "valid",jsonObject.getBoolean("VALID"),
                            "version",jsonObject.getString("VERSION")
                    );
                }
        ).collect(Collectors.toList());
        if (result.size() == 0 ){
            throw new RuntimeException("未找到满足条件得数据!!!");
        }
        return  result;
    }

    /**
     * 放弃编辑回显当前数据
     * @param request
     * @return
     */
    public Map stockConfigFindOne(SimpleRequest request){
        List<BrandPriority> list = request.getA("stockConfigItems", StockConfig.class);
        return MapUtil.mapper("stockConfigItems",list);
    }

}
